<template>
  <ContentWrap :bodyStyle="{ paddingTop: '5px' }" class="data-source-task">
    <back :backOption="backOption" />
    <div class="data-source-result-wrap h-full">
      <el-card shadow="hover" class="mt-16px">
        <template #header>
          <span>{{ infoOptions.data.taskName || '--' }}</span>
        </template>
        <ns-descriptions v-bind="infoOptions" />
      </el-card>
      <el-card shadow="hover" class="mt-16px p-16px">
        <el-form :model="formOption.data" ref="secondformEl" label-width="110px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="数据源名称" prop="datasourceName">
                <ns-input
                  placeholder="请输入数据源名称"
                  v-model="formOption.data.datasourceName"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="资产IP" prop="ip">
                <ns-input placeholder="请输入资产IP" v-model="formOption.data.ip" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="端口" prop="port">
                <ns-input placeholder="请输入端口" v-model="formOption.data.port" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="资产类型:" prop="assetType">
                <el-select
                  v-model.trim="formOption.data.assetType"
                  class="w-full"
                  popper-class="select-no-dropdown"
                  placeholder="请选择资产类型"
                  @click="showAssetSelect"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="归属机构" prop="deptId">
                <el-cascader
                  v-model="formOption.data.deptId"
                  placeholder="请选择归属机构"
                  :props="formOption.cascaderProps"
                  :options="formOption.deptList"
                  filterable
                  clearable
                  :filter-method="sysFilterMethod"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="归属系统" prop="sysId">
                <el-cascader
                  v-model="formOption.data.sysId"
                  placeholder="请选择归属系统"
                  :props="formOption.systemCascaderProps"
                  :options="formOption.systemList"
                  filterable
                  clearable
                  :filter-method="sysFilterMethod"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="入库状态" prop="storageStatus">
                <el-select
                  placeholder="请选择入库状态"
                  v-model="formOption.data.storageStatus"
                  clearable
                >
                  <el-option
                    :label="item"
                    :value="key"
                    :key="'storageStatus' + key"
                    v-for="(item, key) in formOption.statusList"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="数据源类型" prop="datasourceType">
                <el-select
                  v-model="formOption.data.datasourceType"
                  clearable
                  placeholder="请选择数据源类型"
                >
                  <el-option label="数据库" :value="1" />
                  <el-option label="文件服务器" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="最近执行时间" prop="startTime">
                <el-date-picker
                  v-model="formOption.data.startTime"
                  type="datetimerange"
                  range-separator="到"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
            </el-col>
            <el-col :span="18" class="text-right">
              <el-button type="primary" @click="query">搜索</el-button>
              <el-button @click="resetSearch"> 重置 </el-button>
            </el-col>
          </el-row>
        </el-form>
        <el-form-item>
          <el-button
            type="primary"
            :disabled="disabledAddRows"
            @click="handleAdd(taskData.infos, 'batch')"
            >批量加入数据源</el-button
          >
          <el-button type="danger" @click="handleDel" :disabled="taskData.ids.length === 0"
            >删除</el-button
          >
        </el-form-item>
        <AsyncTable
          v-bind="colums"
          ref="tableRef"
          :fetchData="fetchData"
          @selection-change="handleSelectionChange"
        />
      </el-card>
    </div>
    <Add
      v-if="addOption.show"
      v-model="addOption.show"
      :info="addOption.info"
      @submit="addSubmit"
    />
    <asset-select
      v-if="assetOption.show"
      v-model="assetOption.show"
      @update-asset-type="updateAssetType"
    />
  </ContentWrap>
</template>
<script setup lang="tsx">
import { sysFilterMethod } from '@/utils/selectFilter'
import back from '@/components/Back/index.vue'
import assetSelect from '@/views/asset/components/AssetSelect.vue'
import Add from './dataSourceTask/add.vue'
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { handleTree } from '@/utils/tree'
import { ElButton } from 'element-plus'
import { Hide, View, Edit } from '@element-plus/icons-vue'
import * as api from '@/api/asset/taskManage'
import {
  getBaseInfo,
  getList,
  addDataSource,
  updateAsset,
  delResultItem
} from '@/api/asset/taskManage/dataSource'
import { getSimpleDeptList } from '@/api/system/dept'
const { proxy } = getCurrentInstance()
const allSelect = ref(false)
const tableRef = ref()
const isEdit = ref(false)
const route = useRoute()
const backOption = reactive({
  title: '数据源探测结果'
})
const assetOption = reactive({
  show: false,
  info: {}
})
const addOption = reactive({
  show: false,
  isAdd: false,
  type: '',
  info: {}
})
const secondformEl = ref()
const rowId = ref('')
const disabledAddRows = ref(true)
const taskData = reactive({
  ids: [],
  infos: []
})
const infoOptions = reactive({
  border: false,
  column: 3,
  labelSuffix: '：',
  labelWidth: '140px',
  columns: [
    { label: '启动时间', key: 'startTime' },
    { label: '完成时间', key: 'finishTime' },
    { label: '执行人', key: 'executorName' },
    { label: '发现数据源数', key: 'datasourceNum' },
    { label: '发现数据库数', key: 'databaseNum' },
    { label: '发现文件服务器数', key: 'fileServerNum' }
  ],
  data: []
})
const formOption = reactive({
  data: {
    deptId: '',
    sysId: '',
    ip: '',
    port: '',
    datasourceName: '',
    storageStatus: '',
    assetType: '',
    datasourceType: '',
    startTime: []
  },
  systemList: [],
  deptList: [],
  statusList: {
    0: '未添加',
    1: '已添加'
  },
  systemCascaderProps: {
    checkStrictly: true,
    label: 'value',
    value: 'id',
    children: 'children',
    emitPath: false
  },
  cascaderProps: {
    checkStrictly: true,
    label: 'name',
    value: 'id',
    children: 'children',
    emitPath: false
  }
})
const handleDel = () => {
  proxy.$modal.confirm(`确定要删除吗？`).then(() => {
    delResultItem({ idList: taskData.ids }).then(({ code }) => {
      code === 200 && ElMessage.success('删除成功')
      code === 200 && tableRef.value.resetPage()
      code === 200 && tableRef.value.fetchData()
    })
  })
}
const handleShowIp = (row) => {
  row.isShowIp = !row?.isShowIp
}
const colums = computed(() => {
  return {
    columns: [
      {
        type: 'selection',
        width: '40px'
      },
      {
        label: '数据源名称',
        width: 250,
        render: ({ row }) => {
          return row.storageStatus === 1 ? (
            <span>{row.datasourceName}</span>
          ) : (
            <ns-input
              placeholder="请输入数据源名称"
              v-model={row.dataSourceName}
              clearable
            ></ns-input>
          )
        }
      },
      {
        label: '资产IP:端口',
        width: '170px',
        'show-overflow-tooltip': true,
        render: ({ row }) => {
          return (
            <>
              <div style="display:flex;align-items:center;justify-content:space-between;">
                {row?.isShowIp ? (
                  <span>{row.port ? row.ip + ':' + row.port : row.ip}</span>
                ) : (
                  <span style="font-size:17px">***********</span>
                )}
                {row?.isShowIp ? (
                  <el-icon>
                    <Hide onClick={() => handleShowIp(row)} />
                  </el-icon>
                ) : (
                  <el-icon>
                    <View onClick={() => handleShowIp(row)} />
                  </el-icon>
                )}
              </div>
            </>
          )
        }
      },
      {
        label: '资产类型',
        render: ({ row }) => {
          if (row.assetType) {
            return (
              <>
                <span>{row.assetType}</span>
                <span onClick={() => showAssetSelect(row)}>
                  <el-icon>
                    <Edit />
                  </el-icon>
                </span>
              </>
            )
          } else return '--'
        }
      },
      {
        label: '归属机构',
        prop: 'department'
      },
      {
        label: '归属系统',
        prop: 'system'
      },
      {
        label: '扫描时间',
        prop: 'scanTime',
        width: 190,
        'show-overflow-tooltip': true
      },
      {
        label: '入库状态',
        prop: 'storageStatus',
        render: (cellData) => {
          return (
            <span style={{ color: cellData ? '#409EFF' : '#F56C6C' }}>
              {formOption.statusList[cellData]}
            </span>
          )
        }
      },
      {
        label: '操作项',
        fixed: 'right',
        width: 150,
        render: ({ row }) => {
          return (
            <div class="operate-btn">
              <el-button
                type="primary"
                size="small"
                text
                onClick={() => handleAdd(row, 'single')}
                disabled={row.storageStatus}
              >
                加入数据源
              </el-button>
            </div>
          )
        }
      }
    ],
    data: []
  }
})

async function handleAdd(row, type) {
  if (row && Array.isArray(row)) {
    const isAdd = row.some((item) => {
      return item.storageStatus === 1
    })
    const isHaveName = row.some((item) => {
      return !item.dataSourceName
    })
    if (isAdd) {
      ElMessage.error('已入库的探测结果不能再次添加')
      return
    }
    if (isHaveName) {
      ElMessage.error('请输入数据源名称')
      return
    }
    addOption.show = true
    isEdit.value = true
    const idAndNames = []
    row.forEach((item) => {
      idAndNames.push({ name: item.dataSourceName, id: item.id })
    })
    addOption.info = {
      deptId: row[0]?.deptId,
      sysId: row[0]?.sysId,
      type,
      idAndNames
    }
  } else if (row) {
    addOption.show = true
    isEdit.value = true
    addOption.info = {
      idAndNames: [{ id: row.id, name: row.dataSourceName || '' }],
      deptId: row.deptId,
      sysId: row.sysId,
      type
    }
  } else {
    isEdit.value = false
    addOption.info = {}
  }
}

// 加入数据源提交
const addSubmit = async (data) => {
  let params = {}
  if (data.type === 'single') {
    data.idAndNames[0].name = data.name
    delete data.name
    delete data.type
  }
  if (isEdit.value) {
    params = {
      taskId: route.query.id,
      ...data
    }
  } else {
    params = {
      taskId: route.query.id,
      idList: taskData.ids,
      allSelect: allSelect.value,
      ...data
    }
  }
  const { code } = await addDataSource(params)
  code === 200 && ElMessage.success('加入数据源成功')
  code === 200 && query()
}
function resetSearch() {
  secondformEl.value.resetFields()
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}

async function fetchData({ page, pageSize }) {
  const res = await getList({
    ...formOption.data,
    taskId: route.query.id,
    page,
    pageSize
  })
  return {
    rows: res.data,
    count: res.count
  }
}

function showAssetSelect(row) {
  if (row) rowId.value = row.id
  else rowId.value = ''
  assetOption.show = true
}

async function updateAssetType(sql) {
  if (rowId.value) {
    await updateAsset({
      id: rowId.value,
      assetType: sql.showName
    })
    query()
  } else {
    formOption.data.assetType = sql.showName
  }
  assetOption.show = false
}

function handleSelectionChange(rows) {
  disabledAddRows.value = !rows.length
  taskData.ids = rows.map((item) => item.id)
  taskData.infos = rows
}

const query = () => {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}

async function getDeptList() {
  const data = await getSimpleDeptList()
  formOption.deptList = data
}

async function getSystemList() {
  const data = await api.getSimpleSystemList()
  formOption.systemList = handleTree(data, 'id', 'pid')
}

async function getInfo() {
  const data = await getBaseInfo({
    taskId: route.query.id
  })
  infoOptions.data = data || {}
}

onMounted(() => {
  getDeptList()
  getSystemList()
  getInfo()
})
</script>

<style lang="scss">
.data-source-task {
  .data-source-result-wrap {
    .el-card__header {
      padding: 10px 16px;
    }
    .el-card__body {
      padding: 20px 0px;
    }
    .el-descriptions__table {
      width: 100%;
    }
    .el-descriptions__label {
      color: #606266;
    }
    .el-descriptions__content {
      font-size: 14px;
      vertical-align: top;
      color: #606266;
    }
  }
  .el-form {
    .ns-input,
    .el-select,
    .el-cascader {
      width: 100%;
    }
  }
  .select-no-dropdown {
    display: none;
  }
}
</style>
